package init

import (
	"doctor-server/basic/config"
	"doctor-server/handler/models"
	"fmt"

	"github.com/spf13/viper"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func init() {
	ConfigInit()
	MysqlInit()
}

func ConfigInit() {
	var err error
	viper.SetConfigFile("../config/config.yaml")
	err = viper.ReadInConfig()

	err = viper.Unmarshal(&config.ConfigDate)
	if err != nil {
		panic(err)
	}
	fmt.Println("数据配置成功", config.ConfigDate)

}

func MysqlInit() {
	var err error
	con := config.ConfigDate.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		con.User,
		con.Password,
		con.Host,
		con.Port,
		con.Database,
	)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("连接成功")
	err = config.DB.AutoMigrate(&models.User{})
	if err != nil {
		panic(err)
	}
	fmt.Println("迁移成功")

}
